package com.jzo2o.customer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.CurrentUserInfo;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.common.utils.JwtTool;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mysql.utils.PageUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Autowired
    JwtTool jwtTool;

    @Autowired
    AddressBookMapper addressBookMapper;

    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if(CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }

    @Override
    public PageResult<AddressBook> selectByUserId(AddressBookPageQueryReqDTO addressBookPageQueryReqDTO, Long id) {
        //通过id查询地址列表,对列表进行分页
        Page<AddressBook> page = PageUtils.parsePageQuery(addressBookPageQueryReqDTO, AddressBook.class);
        //根据ID查询
        QueryWrapper<AddressBook> addressBookQueryWrapper = new QueryWrapper<>();
        addressBookQueryWrapper.lambda().eq(AddressBook::getUserId, id);
        Page<AddressBook> addressBookPage = baseMapper.selectPage(page, addressBookQueryWrapper);
        return PageUtils.toPage(addressBookPage, AddressBook.class);


    }

    @Override
    public void add(AddressBook addressBook, String token) {
        //解析token
        CurrentUserInfo currentUserInfo = jwtTool.parseToken(token);
        //token为空不允许添加
        if(currentUserInfo == null) {
            throw new ForbiddenOperationException("token为空不允许添加");
        }

        List<AddressBook> addressBookList = addressBookMapper.selectListById(addressBook.getId());
        //循环地址列表,如果有默认值不允许重复设置默认值
        for (AddressBook addressBook1 : addressBookList) {
            if(addressBook1.getIsDefault() == 1) {
                throw new ForbiddenOperationException("默认地址只能设置一个");
            }
        }
        Long id = currentUserInfo.getId();
        addressBook.setUserId(id);
        int insert = baseMapper.insert(addressBook);

        if(insert != 1) {
            throw new ForbiddenOperationException("添加失败");
        }


    }

    @Override
    public AddressBook addressBookById(Long id) {


        //根据Id获取地址
        return baseMapper.selectById(id);
    }

    @Override
    public AddressBook updateAddressBook(AddressBook addressBook) {
        //通过Id查询地址信息
        AddressBook addressBook1 = baseMapper.selectById(addressBook.getId());
        if(addressBook1 == null) {
            throw new ForbiddenOperationException("地址不存在");
        }
        //修改地址信息
        int update = baseMapper.updateById(addressBook);
        if(update != 1) {
            throw new ForbiddenOperationException("修改失败");
        }
        return baseMapper.selectById(addressBook.getId());
    }

    @Override
    public AddressBook deleteByIds(String[] ids) {


        //通过ids进行删除地址
        int i = baseMapper.deleteBatchIds(CollUtils.toList(ids));
        if(i != 1) {
            throw new ForbiddenOperationException("删除失败");
        }
        return null;
    }

    @Override
    public AddressBook setDefault(Long id, Integer flag) {
        //根据Id查询地址
        AddressBook addressBook = baseMapper.selectById(id);
        if(addressBook == null) {
            throw new ForbiddenOperationException("地址不存在");
        }

        List<AddressBook> addressBookList = addressBookMapper.selectListById(id);
        if (flag==1) {
            //循环地址列表,如果有默认值不允许重复设置默认值
            for (AddressBook addressBook1 : addressBookList) {
                if (addressBook1.getIsDefault() == 1) {
                    throw new ForbiddenOperationException("默认地址只能设置一个");
                }
            }
        }
        //设置默认地址
        AddressBook addressBook1 = new AddressBook().setIsDefault(flag).setId(id);

        boolean b = updateById(addressBook1);
        if(!b) {
            throw new ForbiddenOperationException("设置失败");
        }
        return baseMapper.selectById(id);
    }

    @Override
    public AddressBook getDefaultAddress(String token) {

        //token为空不能获取
        if(StringUtils.isEmpty(token)) {
            throw new ForbiddenOperationException("token为空不能获取");
        }

        //解析token
        CurrentUserInfo currentUserInfo = jwtTool.parseToken(token);

        Long id = currentUserInfo.getId();

        //获取地址ID为ID的默认地址
        return addressBookMapper.getDefaultAddress(id);
    }
}
